<template>
  <el-card>
    <el-row :gutter="20" class="header">
      <el-col :span="8">
        <el-input placeholder="请输入公告标题" clearable v-model="queryForm.title" />
      </el-col>
      <el-col :span="8">
        <el-select v-model="queryForm.type" placeholder="公告类型" clearable>
          <el-option label="系统公告" :value="1" />
          <el-option label="活动公告" :value="2" />
        </el-select>
      </el-col>
      <el-col :span="8">
        <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
        <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
    </el-row>

    <el-table :data="tableData" style="width: 100%" v-loading="loading">
      <el-table-column prop="title" label="公告标题" />
      <el-table-column prop="content" label="内容" :show-overflow-tooltip="true" />
      <el-table-column prop="create_time" label="发布时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.create_time) }}
        </template>
      </el-table-column>
      <el-table-column prop="is_recommend" label="推荐状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.is_recommend === 1 ? 'success' : 'info'">
            {{ row.is_recommend === 1 ? '已推荐' : '未推荐' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280">
        <template #default="{ row }">
          <el-button type="success" size="small" :icon="View" @click="handleView(row)" />
          <el-button
            :type="row.is_recommend === 1 ? 'warning' : 'waring'"
            size="small"
            :icon="Star"
            @click="handleRecommend(row)"
          />
          <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)" />
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="queryForm.page"
      v-model:page-size="queryForm.size"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>

  <Dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    :form="currentForm"
    @success="handleSuccess"
  />
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search, Plus, Delete, View, Star } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Dialog from './components/dialog.vue'
import noticeApi from '@/api/notice'

const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const currentForm = ref({
  notice_id: 0,
  title: '',
  content: '',
  type: 1
})
const total = ref(0)

const queryForm = ref({
  page: 1,
  size: 10,
  title: '',
  type: ''
})

const tableData = ref([])

// 添加时间格式化函数
const formatDateTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 获取列表数据
const getList = async () => {
  try {
    loading.value = true
    const { data } = await noticeApi.getNoticeList(queryForm.value)
    if (data) {
      if (Array.isArray(data)) {
        tableData.value = data
        total.value = data.length
      } else {
        ElMessage.error('获取公告列表失败')
      }
    } else {
      ElMessage.error('获取公告列表失败')
    }
  } catch (error) {
    console.error('获取列表失败:', error)
    ElMessage.error('获取列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryForm.value.page = 1
  getList()
}

// 新增
const handleAdd = () => {
  currentForm.value = {
    notice_id: 0,
    title: '',
    content: '',
    type: 1
  }
  dialogTitle.value = '新增公告'
  dialogVisible.value = true
}

// 查看
const handleView = async (row) => {
  try {
    const { data } = await noticeApi.getNoticeDetail(row.notice_id)
    if (data) {
      // 显示详情
      ElMessageBox.alert(data.content, data.title, {
        confirmButtonText: '确定'
      })
    }
  } catch (error) {
    console.error('获取公告详情失败:', error)
    ElMessage.error('获取公告详情失败')
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该公告?', '提示', {
      type: 'warning'
    })
    const { data } = await noticeApi.updateNotice(row.notice_id, {
      is_delete: 1
    })
    if (data) {
      ElMessage.success('删除成功')
      getList()
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

// 分页
const handleSizeChange = (size) => {
  queryForm.value.page = 1
  queryForm.value.size = size
  getList()
}

const handleCurrentChange = (page) => {
  queryForm.value.page = page
  getList()
}

// 表单提交成功
const handleSuccess = () => {
  getList()
}

// 推荐/取消推荐
const handleRecommend = async (row) => {
  try {
    const newStatus = row.is_recommend === 1 ? 0 : 1
    const { data } = await noticeApi.updateNotice(row.notice_id, {
      is_recommend: newStatus
    })
    if (data) {
      ElMessage.success(newStatus === 1 ? '已设为推荐' : '已取消推荐')
      getList()
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.header {
  padding: 16px;
  box-sizing: border-box;
}

:deep(.el-pagination) {
  margin-top: 16px;
  justify-content: center;
}

.el-tag {
  width: 65px;
  text-align: center;
}

.el-select {
  width: 100%;
}
</style>
